package com.compass.doctor.ui.patient.fragment

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.ListPopupWindow
import androidx.fragment.app.viewModels
import com.compass.doctor.base.BaseVBFragment
import com.compass.doctor.callback.OnAddExaminationCallBack
import com.compass.doctor.callback.OnCustomItemClick
import com.compass.doctor.databinding.FragmentInspectBinding
import com.compass.doctor.ui.chat.util.sendExamineMessage
import com.compass.doctor.ui.patient.ExecutiveDepartmentActivity
import com.compass.doctor.ui.patient.InspectionItemActivity
import com.compass.doctor.ui.patient.SampleBodyActivity
import com.compass.doctor.ui.patient.adapter.InpatientPopupAdapter
import com.compass.doctor.ui.patient.viewmodel.ExamineViewModel
import com.compass.doctor.ui.prescription.DiagnoseActivity
import com.compass.framework.R
import com.compass.framework.constant.KEY_CONSULT_TYPE
import com.compass.framework.constant.KEY_SESSION_ID
import com.compass.framework.constant.KEY_PATIENT_ID
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.onClick
import com.compass.framework.model.CreateInspection
import com.compass.framework.model.Diagnosis
import com.compass.framework.model.InpatientWard
import com.compass.framework.utils.getStringFromResource

/**
 * Description： 检验 Frgament
 * Date:2024/3/7 11:38
 */
class InspectFragment : BaseVBFragment<FragmentInspectBinding>() {


    private var requestType: Int = 1//请求type
    private var type: String = "1" //1-检验 2-检查
    private lateinit var patientId: String//患者ID
    private lateinit var sessionId: String//患者云信账号


    private val examineViewModel: ExamineViewModel by viewModels()
    private var diagnosis: Diagnosis? = null//接收返回的诊断数据
    private var inspectionItem: Diagnosis? = null//检查项目
    private var sample: Diagnosis? = null//标本
    private var department: InpatientWard? = null//科室
    private var departmentHisCode: String? = null//执行科室
    private var departmentHisName: String? = null//执行科室
    private var bodyCode: String? = null//标本类型code/部位code

    private var onExaminationCallBack: OnAddExaminationCallBack? = null

    //诊断回调/检查项目回调
    private val mActivityResultLauncher: ActivityResultLauncher<Intent> =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == AppCompatActivity.RESULT_OK) {
                it.data?.let { intent ->

                    when (requestType) {
                        1 -> {
                            diagnosis = intent.serializable("diagnosis")
                            mBinding?.tvDiagnose?.text = diagnosis?.name
                        }

                        2 -> {
                            inspectionItem = intent.serializable("diagnosis")
                            mBinding?.tvInspectionItem?.text = inspectionItem?.name
                            showLoading()
                            examineViewModel.getInspectionDepartments(inspectionItem?.id)
                            mBinding?.tvDepartments?.text = ""//清空执行科室
                            departmentHisCode = null
                            departmentHisName = null
                            bodyCode = null
                            mBinding?.tvSpecimen?.text = ""//清空标本类型

                        }

                        3 -> {
                            sample = intent.serializable("diagnosis")
                            bodyCode = sample?.id
                            mBinding?.tvSpecimen?.text = sample?.name

                        }

                        4 -> {
                            department = intent.serializable("department")
                            department?.let { item ->
                                departmentHisName = item.name
                                departmentHisCode = item.code
                                setDepartment(item)
                            }

                        }

                        else -> {}
                    }

                }
            }
        }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        arguments?.let {
            patientId = it.getString(KEY_PATIENT_ID)!!
            sessionId = it.getString(KEY_SESSION_ID)!!
        }

    }


    fun setOnExaminationCallBack(onAddExaminationCallBack: OnAddExaminationCallBack) {
        onExaminationCallBack = onAddExaminationCallBack
    }

    private fun setDepartment(department: InpatientWard) {

        mBinding?.tvDepartments?.text = departmentHisName
        if (!department.sampType.isNullOrEmpty() && !department.sampTypeName.isNullOrEmpty() && bodyCode.isNullOrEmpty()) {

            mBinding?.tvSpecimen?.text = department.sampTypeName
            bodyCode = department.sampType

        }
    }


    override fun intListener() {


        mBinding?.tvInspectionItem?.onClick {
            requestType = 2
            val intent = Intent(requireContext(), InspectionItemActivity::class.java)
            intent.putExtra(KEY_CONSULT_TYPE, type)
            mActivityResultLauncher.launch(intent)
        }
        mBinding?.tvSpecimen?.onClick {
            requestType = 3
            val intent = Intent(requireContext(), SampleBodyActivity::class.java)
            intent.putExtra(KEY_CONSULT_TYPE, type)
            mActivityResultLauncher.launch(intent)

        }


        mBinding?.tvDepartments?.onClick {
            requestType = 4
            val intent = Intent(requireContext(), ExecutiveDepartmentActivity::class.java)
            mActivityResultLauncher.launch(intent)

        }
        mBinding?.tvSubmit?.onClick {
            createInspection()
        }

    }


    override fun initData() {
        examineViewModel.departmentsLiveData.observe(this) {
            dismissLoading()
            if (!it.isNullOrEmpty()) {
                val inpatientWard = it[0]
                departmentHisName = inpatientWard.name
                departmentHisCode = inpatientWard.id
                setDepartment(inpatientWard)
            }
        }
    }


    fun createInspection() {

        val inspectionId = inspectionItem?.id
        val inspectionName = inspectionItem?.name
        if (inspectionId.isNullOrEmpty()) {
            showToast("请选择检验项目")
            return
        }
        if (departmentHisCode.isNullOrEmpty()) {
            showToast("请选择执行科室")
            return
        }

        if (bodyCode.isNullOrEmpty()) {
            showToast("请选择标本类型")
            return
        }

        val doctorAdvice = mBinding?.edtDoctorAdvice?.text.toString().trim()

        val createInspection = CreateInspection(
            patientId,
            departmentHisCode,
            departmentHisName,
            inspectionId,
            inspectionName,
            doctorAdvice,
            bodyCode,
            type
        )


//        CommonMessageDialog.Builder(requireActivity())
//            .setTitle(getStringFromResource(R.string.dialog_tips_title))
//            .setMessage("是否添加？")
//            .setConfirm(getStringFromResource(R.string.default_confirm))
//
//            .setCancel(getString(com.compass.framework.R.string.default_cancel))
//            .setonCancelListener {
//                it?.dismiss()
//            }
//            .setonConfirmListener {
//
//                it?.dismiss()
//            }.create().show()


        inspectionItem = null
        mBinding?.tvInspectionItem?.text = ""//清空项目
        mBinding?.tvDepartments?.text = ""//清空执行科室
        departmentHisCode = null
        departmentHisName = null
        bodyCode = null
        mBinding?.tvSpecimen?.text = ""//清空标本类型
        onExaminationCallBack?.onExaminationCallBack(createInspection)


    }


}